<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GoZero 聊天</title>
    <script src="/static/common.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4F46E5',
                        secondary: '#818CF8',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .message-in {
                animation: bubbleIn 0.25s cubic-bezier(.4,2,.6,1) both;
            }
            @keyframes bubbleIn {
                0% { opacity: 0; transform: scale(0.95) translateY(20px);}
                100% { opacity: 1; transform: scale(1) translateY(0);}
            }
            .avatar-optimized {
                width: 40px; height: 40px;
                border-radius: 50%;
                background: linear-gradient(135deg,#6366f1,#818cf8);
                display: flex; align-items: center; justify-content: center;
                font-size: 1.5rem; font-weight: bold; color: #fff;
                box-shadow: 0 2px 8px rgba(80,80,180,0.12);
                border: 2px solid #fff;
                overflow: hidden;
            }
            .avatar-optimized img { width: 100%; height: 100%; border-radius: 50%; object-fit: cover; }
            /* 新增美化样式 */
            .modern-gradient {
                background: linear-gradient(135deg, #e0e7ff 0%, #f8fafc 100%);
            }
            .modern-card {
                @apply rounded-2xl shadow-xl bg-white/90 backdrop-blur-md;
            }
            .modern-btn {
                @apply rounded-full shadow-md bg-gradient-to-r from-primary to-secondary text-white font-semibold transition-all duration-200;
            }
            .modern-btn:hover {
                @apply from-secondary to-primary scale-105 shadow-lg;
            }
            .modern-input {
                @apply rounded-full shadow-sm border-2 border-gray-200 focus:border-primary focus:ring-2 focus:ring-primary/30 transition-all duration-200 px-4 py-2;
            }
            .modern-nav {
                background: linear-gradient(90deg, #6366f1 0%, #818cf8 100%);
                @apply shadow-lg backdrop-blur-md;
            }
            .modern-sidebar {
                @apply bg-white/80 shadow-lg rounded-2xl backdrop-blur-md w-full h-[calc(100vh-160px)];
            }
            .chat-bubble-left {
                @apply bg-gray-100 text-gray-800 rounded-2xl shadow p-3 max-w-[80%] mr-auto mb-2;
            }
            .chat-bubble-right {
                @apply bg-gradient-to-br from-primary to-secondary text-white rounded-2xl shadow p-3 max-w-[80%] ml-auto mb-2;
            }
            .read-status-row {
                font-size: 12px;
                color: #94a3b8;
                opacity: 0.85;
                margin-top: 2px;
                text-align: right;
                min-width: 80px;
            }
            .message-in {
                min-width: 80px;
                min-height: 36px;
                padding: 8px 16px;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-gray-800 min-h-screen flex flex-col">
  <!-- 移动端顶部栏 -->
  <header class="lg:hidden flex items-center justify-between px-4 py-3 bg-white shadow z-20 sticky top-0">
    <button id="mobile-menu-btn" class="text-primary text-2xl"><i class="fa fa-bars"></i></button>
    <span class="font-bold text-lg text-primary">GoZero 聊天</span>
    <div>
      <a id="mobile-login-btn" href="/static/profile.html" class="modern-btn px-3 py-1 text-sm hidden">登录</a>
      <button id="mobile-logout-btn" class="modern-btn px-3 py-1 text-sm hidden">退出</button>
    </div>
  </header>
  <div class="flex h-screen">
    <!-- 侧边栏遮罩，仅移动端显示 -->
    <div id="sidebar-overlay" class="fixed inset-0 bg-black/30 z-20 hidden lg:hidden"></div>
    <!-- 侧边栏，移动端可收起 -->
    <aside id="sidebar" class="w-72 bg-white shadow-lg flex flex-col fixed lg:static z-30 h-full top-0 left-0 transition-transform duration-300 -translate-x-full lg:translate-x-0">
      <div class="flex items-center h-16 px-6 border-b">
        <i class="fa fa-comments text-primary text-2xl mr-2"></i>
        <span class="font-bold text-xl text-primary">GoZero 聊天</span>
      </div>
      <nav class="flex-1 flex flex-col py-4 space-y-2">
        <button id="tab-rooms" class="tab-btn text-left px-6 py-2 font-medium text-gray-700 hover:bg-primary/10 rounded">房间</button>
        <button id="tab-friends" class="tab-btn text-left px-6 py-2 font-medium text-gray-700 hover:bg-primary/10 rounded">好友</button>
        <button id="tab-logs" class="tab-btn text-left px-6 py-2 font-medium text-gray-700 hover:bg-primary/10 rounded">日志</button>
        <button id="tab-profile" class="tab-btn text-left px-6 py-2 font-medium text-gray-700 hover:bg-primary/10 rounded">个人中心</button>
        <button id="tab-games" class="tab-btn text-left px-6 py-2 font-medium text-gray-700 hover:bg-primary/10 rounded">游戏空间</button>
      </nav>
    </aside>
    <!-- 主内容区：响应式，移动端全屏，桌面端分栏 -->
    <div class="flex-1 flex flex-col lg:ml-72">
      <!-- 顶部导航栏和公告横幅保留 -->
      <header class="modern-nav text-white shadow-md hidden lg:block">
            <div class="container mx-auto px-4 py-3 flex justify-between items-center">
                <h1 class="text-xl font-bold flex items-center">
                    <i class="fa fa-comments-o mr-2"></i>GoZero 聊天
                </h1>
                <div class="flex items-center space-x-4">
                    <div id="user-info" class="flex items-center">
                        <span id="current-user" class="mr-2 cursor-pointer hover:underline"></span>
                        <a id="login-btn" href="/static/profile.html" class="modern-btn px-3 py-1 text-sm hidden">登录</a>
                        <button id="logout-btn" class="modern-btn bg-white text-primary px-3 py-1 rounded text-sm hover:bg-gray-100 transition-colors hidden">
                            <i class="fa fa-sign-out mr-1"></i>退出
                        </button>
                    </div>
                    <a href="static/game-lobby.html" id="game-btn" class="bg-white text-primary px-3 py-1 rounded text-sm hover:bg-gray-100 transition-colors flex items-center">
                        <i class="fa fa-gamepad mr-1"></i>游戏空间
                    </a>
                </div>
            </div>
        </header>
        <!-- 公告横幅 -->
        <div id="announcement-banner" class="bg-gradient-to-r from-yellow-100 to-yellow-50 border-b border-yellow-200 shadow-sm hidden">
            <div class="container mx-auto px-4 py-3 flex items-center justify-between">
                <div class="flex items-center">
                    <i class="fa fa-bullhorn text-yellow-600 mr-2"></i>
                    <span id="announcement-text" class="text-yellow-800 font-medium"></span>
                </div>
                <button id="close-announcement" class="text-yellow-600 hover:text-yellow-800">
                    <i class="fa fa-times"></i>
                </button>
            </div>
        </div>
      <!-- 主内容区Tab面板 -->
      <main class="flex-grow container mx-auto px-2 sm:px-4 py-2 sm:py-6">
        <div id="rooms-panel">
          <div class="flex flex-col sm:flex-row items-center justify-between mb-4 gap-2">
            <h2 class="text-xl font-bold flex items-center"><i class="fa fa-th-large mr-2 text-primary"></i>房间列表</h2>
            <button id="create-room-btn" class="modern-btn py-2 px-4 w-full sm:w-auto"><i class="fa fa-plus mr-1"></i>创建房间</button>
                    </div>
          <div class="mb-4">
                                <input type="text" id="room-search" class="modern-input w-full pl-9 pr-3" placeholder="搜索房间...">
                                <script>
                                  document.getElementById('room-search').addEventListener('input', function(e) {                                    const searchTerm = e.target.value.trim().toLowerCase();
                                    searchRooms(searchTerm);
                                  });

                                  // 添加好友按钮事件
                                  document.getElementById('add-friend-btn').addEventListener('click', function() {
                                    const friendId = document.getElementById('add-friend-input').value.trim();
                                    if (friendId) {
                                      addFriend(friendId);
                                    } else {
                                      alert('请输入好友ID');
                                    }
                                  });

                                  // 房间搜索函数（保留）
                                  function searchRooms(term) {
                                    const roomsList = document.getElementById('rooms-list');
                                    Array.from(roomsList.children).forEach(room => {
                                      const roomName = room.querySelector('.room-name')?.textContent.toLowerCase() || '';
                                      room.style.display = roomName.includes(term) ? 'block' : 'none';
                                    });
                                  }

                                  // 好友搜索函数 - 保持不变，用于好友列表的搜索过滤
                                  function searchFriends(term) {
                                    const friendsList = document.getElementById('friends-list');
                                    // 这里添加实际搜索逻辑，例如过滤好友列表
                                    // 示例：
                                    Array.from(friendsList.children).forEach(friend => {
                                      const friendName = friend.querySelector('.friend-name')?.textContent.toLowerCase() || '';
                                      const friendId = friend.querySelector('.friend-id')?.textContent.toLowerCase() || '';
                                      friend.style.display = (friendName.includes(term) || friendId.includes(term)) ? 'block' : 'none';
                                    });
                                  }

                                  // 新增添加好友函数
                                  function addFriend(friendId) {
                                    // 显示加载状态
                                    const addBtn = document.getElementById('add-friend-btn');
                                    const originalText = addBtn.textContent;
                                    addBtn.textContent = '添加中...';
                                    addBtn.disabled = true;

                                    // 发送添加好友请求到后端
                                    fetch('/api/friends/add', {
                                      method: 'POST',
                                      headers: {
                                        'Content-Type': 'application/json',
                                      },
                                      body: JSON.stringify({ friendId: friendId })
                                    })
                                    .then(response => response.json())
                                    .then(data => {
                                      if (data.success) {
                                        alert('添加好友请求已发送');
                                        document.getElementById('add-friend-input').value = '';
                                        // 可选：刷新好友列表
                                        loadFriendsList();
                                      } else {
                                        alert('添加失败: ' + (data.message || '未知错误'));
                                      }
                                    })
                                    .catch(error => {
                                      console.error('添加好友失败:', error);
                                      alert('添加好友失败，请重试');
                                    })
                                    .finally(() => {
                                      // 恢复按钮状态
                                      addBtn.textContent = originalText;
                                      addBtn.disabled = false;
                                    });
                                  }
                                </script>
                            </div>
          <div id="rooms-list" class="space-y-2 flex-grow overflow-y-auto scrollbar-hide"></div>
                        </div>
        <div id="friends-panel" class="hidden">
          <h2 class="text-xl font-bold flex items-center mb-4"><i class="fa fa-user mr-2 text-primary"></i>好友列表</h2>
          <div class="flex flex-col sm:flex-row mb-4 gap-2">
                            <input type="text" id="add-friend-input" class="modern-input flex-grow" placeholder="输入好友ID或搜索用户...">
            <button id="add-friend-btn" class="modern-btn py-2 px-4 w-full sm:w-auto">添加好友</button>
                        </div>
          <div id="friends-list" class="space-y-2 flex-grow overflow-y-auto scrollbar-hide"></div>
                        </div>
        <div id="chat-panel" class="hidden h-full w-full">
          <div class="flex flex-col h-full w-full" style="height:100%;min-height:0;">
            <!-- 固定房间信息区 -->
            <div class="flex items-center p-4 bg-white shadow gap-2 flex-shrink-0" style="border-bottom:1px solid #f1f5f9;">
              <button id="back-to-rooms-btn" class="text-primary hover:text-blue-700 rounded-full p-2 mr-2 focus:outline-none focus:ring-2 focus:ring-primary/30 transition-all" title="返回房间列表">
                <i class="fa fa-arrow-left text-xl"></i>
              </button>
              <img id="chat-avatar" src="https://cdn.jsdelivr.net/gh/identicons/jasonlong.png" class="h-10 w-10 rounded-full mr-3" onerror="this.style.display='none'">
                            <div>
                <div class="font-semibold text-lg" id="current-room-name"></div>
                <div class="text-xs text-gray-500" id="current-room-user-count"></div>
                            </div>
                        </div>
            <!-- 消息区自适应高度且只滚动消息 -->
            <div id="messages-container" class="flex-1 min-h-0 overflow-y-auto p-2 sm:p-4 space-y-4 bg-gray-50 custom-scrollbar" style="max-height:100%;">
              <div id="messages"></div>
                                </div>
            <!-- 输入区始终底部，移动端 sticky，桌面端正常 -->
            <div class="p-2 sm:p-4 bg-white border-t flex items-center gap-2 flex-shrink-0 sticky bottom-0 z-20" style="box-shadow:0 -2px 8px 0 rgba(0,0,0,0.02);">
              <button class="text-gray-500 hover:text-primary p-2"><i class="fa fa-smile-o"></i></button>
              <input type="text" id="message-input" class="flex-1 border rounded-full px-4 py-2" placeholder="输入消息...">
              <button id="send-message-btn" class="bg-primary text-white rounded-full h-10 w-10 flex items-center justify-center ml-2"><i class="fa fa-paper-plane"></i></button>
                            </div>
                        </div>
                            </div>
        <div id="logs-panel" class="hidden">
          <h2 class="text-xl font-bold flex items-center mb-4"><i class="fa fa-list-alt mr-2 text-primary"></i>日志系统</h2>
          <div class="flex flex-col sm:flex-row mb-4 gap-2">
            <button id="all-logs-btn" class="px-3 py-1 bg-primary text-white rounded-md text-sm w-full sm:w-auto">全部</button>
            <button id="error-logs-btn" class="px-3 py-1 bg-gray-200 text-gray-700 rounded-md text-sm w-full sm:w-auto">错误</button>
            <button id="operation-logs-btn" class="px-3 py-1 bg-gray-200 text-gray-700 rounded-md text-sm w-full sm:w-auto">操作</button>
            <button id="warning-logs-btn" class="px-3 py-1 bg-gray-200 text-gray-700 rounded-md text-sm w-full sm:w-auto">警告</button>
            <button id="refresh-logs-btn" class="px-3 py-1 bg-gray-200 text-gray-700 rounded-md text-sm w-full sm:w-auto ml-auto"><i class="fa fa-refresh mr-1"></i>刷新</button>
                        </div>
          <div class="mb-4 grid grid-cols-1 gap-2">
                            <input type="text" id="logs-search" class="modern-input w-full" placeholder="搜索日志...">
                            <div class="grid grid-cols-2 gap-2">
                                <div>
                                    <label class="block text-xs font-medium text-gray-700 mb-1">开始时间</label>
                                    <input type="datetime-local" id="logs-start-time" class="modern-input w-full text-sm">
                                </div>
                                <div>
                                    <label class="block text-xs font-medium text-gray-700 mb-1">结束时间</label>
                                    <input type="datetime-local" id="logs-end-time" class="modern-input w-full text-sm">
                                </div>
                            </div>
                        </div>
                        <div class="flex-grow overflow-y-auto bg-white rounded-lg shadow">
                            <table class="min-w-full">
                                <thead class="bg-gray-100 sticky top-0">
                                    <tr>
                                        <th class="py-2 px-2 text-left text-xs">时间</th>
                                        <th class="py-2 px-2 text-left text-xs">类型</th>
                                        <th class="py-2 px-2 text-left text-xs">内容</th>
                                    </tr>
                                </thead>
                                <tbody id="logs-container">
                                    <tr>
                                        <td colspan="3" class="py-4 text-center text-gray-500">加载中...</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
        <div id="profile-panel" class="hidden">
          <h2 class="text-xl font-bold flex items-center mb-4"><i class="fa fa-user-circle mr-2 text-primary"></i>个人中心</h2>
          <div class="modern-card bg-gradient-to-br from-indigo-100 to-white rounded-2xl shadow-xl p-8 flex flex-col items-center max-w-lg mx-auto">
            <img id="profile-avatar" src="https://cdn.jsdelivr.net/gh/identicons/jasonlong.png" class="w-24 h-24 rounded-full shadow-lg mb-4 border-4 border-white" onerror="this.style.display='none'">
            <div class="font-bold text-2xl text-primary mb-1" id="profile-username">昵称</div>
            <div class="text-xs text-gray-400 mb-4" id="profile-userid">ID: 123456</div>
            <div class="flex flex-wrap justify-center gap-4 w-full mb-4">
              <div class="flex flex-col items-center bg-white/80 rounded-xl shadow p-4 min-w-[90px] hover:scale-105 transition">
                <i class="fa fa-user text-primary mb-1"></i>
                <div class="text-lg font-bold text-indigo-600" id="profile-friendcount">0</div>
                <div class="text-xs text-gray-500 mt-1">好友数</div>
              </div>
              <div class="flex flex-col items-center bg-white/80 rounded-xl shadow p-4 min-w-[90px] hover:scale-105 transition">
                <i class="fa fa-comments text-primary mb-1"></i>
                <div class="text-lg font-bold text-indigo-600" id="profile-roomcount">0</div>
                <div class="text-xs text-gray-500 mt-1">房间数</div>
              </div>
                <div class="flex flex-col items-center bg-white/80 rounded-xl shadow p-4 min-w-[90px] hover:scale-105 transition">
                    <i class="fa fa-star text-yellow-400 mb-1"></i>
                    <div class="text-lg font-bold text-indigo-600" id="profile-level">1</div>
                    <div class="text-xs text-gray-500 mt-1">等级</div>
                </div>
                <div class="flex flex-col items-center bg-white/80 rounded-xl shadow p-4 min-w-[90px] hover:scale-105 transition">
                    <i class="fa fa-circle text-green-400 mb-1" id="profile-status-icon"></i>
                    <div class="text-lg font-bold text-indigo-600" id="profile-status">在线</div>
                    <div class="text-xs text-gray-500 mt-1">在线状态</div>
                </div>
              <div class="flex flex-col items-center bg-white/80 rounded-xl shadow p-4 min-w-[90px] hover:scale-105 transition">
                <i class="fa fa-calendar text-primary mb-1"></i>
                <div class="text-lg font-bold text-indigo-600" id="profile-created">-</div>
                <div class="text-xs text-gray-500 mt-1">注册时间</div>
              </div>
            </div>
          </div>
        </div>
        <div id="games-panel" class="hidden">
          <h2 class="text-xl font-bold flex items-center mb-4"><i class="fa fa-gamepad mr-2 text-primary"></i>游戏空间</h2>
          <div class="p-4 flex-1 flex flex-col h-full">
            <p class="text-gray-600">游戏房间列表将在这里显示。</p>
            <div id="matching-rooms-list"></div>
                </div>
            </div>
        </main>

        <!-- 创建房间模态框 -->
        <div id="create-room-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
            <div class="modern-card max-w-md w-full p-6 transform transition-all">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold">创建新房间</h3>
                    <button id="close-modal-btn" class="text-gray-500 hover:text-gray-700">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
                <div class="mb-4">
                    <label for="room-name" class="block text-sm font-medium text-gray-700 mb-1">房间名称</label>
                    <input type="text" id="room-name" class="modern-input w-full" placeholder="请输入房间名称">
                </div>
                <div class="flex justify-end space-x-3">
                    <button id="cancel-create-room-btn" class="modern-btn bg-gray-200 text-gray-700 hover:bg-gray-300 border-none px-4 py-2 mr-2">取消</button>
                    <button id="confirm-create-room-btn" class="modern-btn px-4 py-2">创建</button>
                </div>
            </div>
        </div>

        <!-- 在<body>内合适位置加toast容器 -->
        <div id="toast" class="fixed top-6 right-6 z-50 hidden"></div>

        <div id="matching-rooms-list"></div>
    </div>
  </div>
  <!-- Tab切换JS -->
    <script>
    const allTabs = {
      'tab-rooms': 'rooms-panel',
      'tab-friends': 'friends-panel',
      'tab-logs': 'logs-panel',
      'tab-profile': 'profile-panel',
      'tab-games': 'games-panel'
    };
    function setupTabHandlers() {
      Object.keys(allTabs).forEach(tabId => {
        document.getElementById(tabId).onclick = () => {
        // 关闭聊天WebSocket并重置状态
            if (tabId === 'tab-rooms' && typeof closeChatPanel === 'function') {
              closeChatPanel();
            }
          Object.values(allTabs).forEach(panelId => {
            document.getElementById(panelId).classList.add('hidden');
          });
          document.getElementById(allTabs[tabId]).classList.remove('hidden');
        };
      });
    }
    setupTabHandlers();

    // 新增：关闭聊天面板和WebSocket
    function closeChatPanel() {
      if (ws) { ws.close(); ws = null; }
        if (wsReconnectTimer) {
          clearTimeout(wsReconnectTimer);
          wsReconnectTimer = null;
        }
      document.getElementById('chat-panel').classList.add('hidden');
      currentRoomId = null;
      currentRoomName = '';
      currentRoomUserCount = 0;
    }

    // 移动端侧边栏展开/收起
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    const mobileMenuBtn = document.getElementById('mobile-menu-btn');
    if (mobileMenuBtn && sidebar && sidebarOverlay) {
      mobileMenuBtn.onclick = function() {
        sidebar.classList.toggle('-translate-x-full');
        sidebar.classList.toggle('translate-x-0');
        sidebarOverlay.classList.toggle('hidden');
      };
      // 点击遮罩收起侧边栏
      sidebarOverlay.onclick = function() {
        sidebar.classList.add('-translate-x-full');
        sidebar.classList.remove('translate-x-0');
        sidebarOverlay.classList.add('hidden');
      };
      // 点击任意Tab后自动收起（仅移动端）
      document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.addEventListener('click', () => {
          if (window.innerWidth < 1024) {
            sidebar.classList.add('-translate-x-full');
            sidebar.classList.remove('translate-x-0');
            sidebarOverlay.classList.add('hidden');
          }
            });
        });
      // 新增：点击侧边栏空白处自动隐藏（仅移动端）
      sidebar.addEventListener('click', function(e) {
        if (window.innerWidth < 1024 && e.target === sidebar) {
          sidebar.classList.add('-translate-x-full');
          sidebar.classList.remove('translate-x-0');
        }
      });
    }

    // 全局用户对象
var currentUser = null;
// 页面加载时初始化 currentUser
window.addEventListener('DOMContentLoaded', function() {
            const userStr = localStorage.getItem('gozero_chat_user');
            if (userStr) {
                try {
                    currentUser = JSON.parse(userStr);
                } catch (e) {
                    currentUser = null;
                }
            }
});

    // 拉取房间列表并渲染
        function fetchRooms() {
      showSkeleton('rooms-list', 3);
            fetch('/api/rooms')
        .then(res => res.ok ? res.json() : [])
            .then(rooms => {
          renderRooms(Array.isArray(rooms) ? rooms : []);
        })
        .catch(() => {
                renderRooms([]);
            });
        }
    // Tab切换到房间时自动刷新
    const tabRoomsBtn = document.getElementById('tab-rooms');
    if (tabRoomsBtn) {
        tabRoomsBtn.addEventListener('click', fetchRooms);
        }
        
    // 优化房间卡片渲染
        function renderRooms(rooms) {
        rooms = Array.isArray(rooms) ? rooms : [];
        const roomsList = document.getElementById('rooms-list');
            roomsList.innerHTML = '';
        if (!rooms.length) {
            roomsList.innerHTML = '<div class="text-center p-6 bg-gray-50 rounded-lg border border-gray-200 shadow-sm animate-fade-in">' +
                    '<i class="fa fa-info-circle text-blue-500 text-2xl mb-2"></i>' +
                    '<p class="text-gray-600 font-medium">房间列表为空</p>' +
                    '<p class="text-gray-500 text-sm mt-1">您可以点击上方的"创建房间"按钮创建一个新房间</p>' +
                    '</div>';
                return;
            }
            rooms.forEach(room => {
                if (!room || typeof room !== 'object') return;
            const card = document.createElement('div');
            card.className = 'room-item bg-white rounded-xl shadow-md hover:shadow-xl transition-shadow p-4 flex items-center justify-between cursor-pointer animate-fade-in';
            card.dataset.id = room.id;
            card.dataset.name = room.name;
            // 图标和标识
                let iconHtml = '';
                let isGameRoom = false;
                let gamePage = '';
            let badgeHtml = '';
                if (room.name === 'snake') {
                    iconHtml = '<i class="fa fa-gamepad text-green-500 mr-2"></i>';
                    isGameRoom = true;
                    gamePage = 'snake.html';
                badgeHtml = '<span class="ml-2 px-2 py-0.5 rounded-full text-xs bg-green-100 text-green-700 font-semibold">游戏</span>';
                } else if (room.name === 'gomoku') {
                    iconHtml = '<i class="fa fa-gamepad text-blue-500 mr-2"></i>';
                    isGameRoom = true;
                    gamePage = 'gomoku.html';
                badgeHtml = '<span class="ml-2 px-2 py-0.5 rounded-full text-xs bg-blue-100 text-blue-700 font-semibold">游戏</span>';
                } else if (room.name === 'tictactoe') {
                    iconHtml = '<i class="fa fa-gamepad text-yellow-500 mr-2"></i>';
                    isGameRoom = true;
                    gamePage = 'tictactoe.html';
                badgeHtml = '<span class="ml-2 px-2 py-0.5 rounded-full text-xs bg-yellow-100 text-yellow-700 font-semibold">游戏</span>';
                } else {
                    iconHtml = '<i class="fa fa-comments-o text-primary mr-2"></i>';
                badgeHtml = '';
            }
            // 信息
            card.innerHTML = `
              <div class="flex items-center">
                    ${iconHtml}
                <span class="room-name font-semibold text-lg">${room.name || '未命名房间'}</span>
                ${badgeHtml}
                    <span class="text-xs bg-gray-100 px-2 py-1 rounded-full ml-2">${room.user_count || 0}人</span>
                ${room.end_time ? `<span class="ml-2 text-xs text-red-500" id="room-timer-${room.id}"></span>` : ''}
              </div>
              <div class="flex items-center gap-2">
                ${room.creator_id === (currentUser && currentUser.userId) ? `<button class="del-room-btn text-xs text-red-500 hover:text-white hover:bg-red-500 border border-red-200 rounded px-2 py-1 transition-colors animate-fade-in" data-id="${room.id}"><i class="fa fa-trash"></i></button>` : ''}
                <button class="enter-room-btn modern-btn px-3 py-1 text-sm animate-fade-in">进入</button>
              </div>
            `;
            // 房间倒计时
            if (room.end_time) {
              const timerSpan = card.querySelector(`#room-timer-${room.id}`);
              function updateTimer() {
                const now = Math.floor(Date.now() / 1000);
                let remain = room.end_time - now;
                if (remain < 0) remain = 0;
                const min = Math.floor(remain / 60);
                const sec = remain % 60;
                timerSpan.textContent = `剩余${min}:${sec.toString().padStart(2, '0')}`;
                if (remain > 0) {
                  setTimeout(updateTimer, 1000);
                } else {
                  timerSpan.textContent = '已结束';
                }
              }
              updateTimer();
            }
            // 进入按钮
            card.querySelector('.enter-room-btn').onclick = (e) => {
                e.stopPropagation();
                if (isGameRoom) {
                    window.location.href = `/static/${gamePage}?room_id=${room.id}`;
                } else {
                    joinRoom(room.id, room.name);
                }
            };
            // 删除按钮
            const delBtn = card.querySelector('.del-room-btn');
            if (delBtn) {
                    delBtn.onclick = (e) => {
                        e.stopPropagation();
                        if (confirm('确定要删除该房间吗？')) {
                            fetch(`/api/rooms/${room.id}`, {
                                method: 'DELETE',
                            headers: { 'X-User-Id': currentUser.userId }
                            })
                            .then(res => {
                            if (!res.ok) throw new Error('删除失败');
                                showToast('房间删除成功', 'success');
                                fetchRooms();
                            })
                        .catch(err => showToast(err.message, 'error'));
                    }
                };
            }
            roomsList.appendChild(card);
        });
    }
    // 拉取好友列表并渲染
    function fetchFriends() {
      if (!currentUser) return renderFriends([]);
      showSkeleton('friends-list', 3);
      fetch('/api/friends?user_id=' + currentUser.userId)
        .then(res => res.ok ? res.json() : [])
        .then(friends => {
          renderFriends(Array.isArray(friends) ? friends : []);
        })
        .catch(() => {
          renderFriends([]);
        });
    }
    // Tab切换到好友时自动刷新
    const tabFriendsBtn = document.getElementById('tab-friends');
    if (tabFriendsBtn) {
        tabFriendsBtn.addEventListener('click', fetchFriends);
    }

    // 优化好友卡片渲染
    function renderFriends(friends) {
        friends = Array.isArray(friends) ? friends : [];
        const friendsList = document.getElementById('friends-list');
        friendsList.innerHTML = '';
        if (!friends.length) {
            friendsList.innerHTML = '<div class="text-center p-6 bg-gray-50 rounded-lg border border-gray-200 shadow-sm animate-fade-in">' +
                '<i class="fa fa-user-o text-blue-500 text-2xl mb-2"></i>' +
                '<p class="text-gray-600 font-medium">暂无好友</p>' +
                '<p class="text-gray-500 text-sm mt-1">您可以通过上方输入框添加好友</p>' +
                '</div>';
            return;
        }
        friends.forEach(friend => {
            if (!friend || typeof friend !== 'object') return;
            const card = document.createElement('div');
            card.className = 'friend-item bg-white rounded-xl shadow-md hover:shadow-xl transition-shadow p-4 flex items-center justify-between animate-fade-in';
            card.innerHTML = `
          <div class="flex items-center">
            <i class="fa fa-user-circle text-primary text-2xl mr-2"></i>
            <span class="font-semibold text-lg">${friend.name || friend.id}</span>
            <span class="text-xs bg-gray-100 px-2 py-1 rounded-full ml-2">ID: ${friend.id}</span>
          </div>
          <button class="del-friend-btn text-xs text-red-500 hover:text-white hover:bg-red-500 border border-red-200 rounded px-2 py-1 transition-colors animate-fade-in" data-id="${friend.id}"><i class="fa fa-trash"></i></button>
        `;
        // 删除按钮
        card.querySelector('.del-friend-btn').onclick = (e) => {
            e.stopPropagation();
            if (confirm('确定要删除该好友吗？')) {
                fetch(`/api/friends/${friend.id}`, {
                    method: 'DELETE',
                    headers: { 'X-User-Id': currentUser.userId }
                })
                .then(res => {
                    if (!res.ok) throw new Error('删除失败');
                    showToast('好友删除成功', 'success');
                    fetchFriends();
                })
                .catch(err => showToast(err.message, 'error'));
            }
        };
        friendsList.appendChild(card);
    });
}

// 优化日志表格渲染
function renderLogs(logs) {
    logs = Array.isArray(logs) ? logs : [];
    const logsContainer = document.getElementById('logs-container');
    logsContainer.innerHTML = '';
    if (!logs.length) {
        logsContainer.innerHTML = '<tr><td colspan="3" class="py-6 text-center text-gray-400 animate-fade-in">暂无日志</td></tr>';
        return;
    }
    logs.forEach(log => {
        if (!log || typeof log !== 'object') return;
        const tr = document.createElement('tr');
        tr.className = 'hover:bg-gray-50 transition-colors animate-fade-in';
        tr.innerHTML = `
          <td class="py-2 px-2 text-xs text-gray-700">${log.time || ''}</td>
          <td class="py-2 px-2 text-xs">
            <span class="px-2 py-1 rounded-full text-xs font-semibold ' +
              (log.type === 'error' ? 'bg-red-100 text-red-600' :
               log.type === 'warning' ? 'bg-yellow-100 text-yellow-700' :
               log.type === 'operation' ? 'bg-blue-100 text-blue-700' :
               'bg-gray-100 text-gray-700') + '">' + (log.type || '未知') + '</span>
          </td>
          <td class="py-2 px-2 text-xs text-gray-800">${log.content || ''}</td>
        `;
        logsContainer.appendChild(tr);
    });
}
// 拉取日志列表并渲染
function fetchLogs() {
  if (!currentUser) return renderLogs([]);
  showSkeleton('logs-container', 3);
  fetch('/api/logs?user_id=' + currentUser.userId)
    .then(res => res.ok ? res.json() : [])
    .then(logs => {
      renderLogs(Array.isArray(logs) ? logs : []);
    })
    .catch(() => {
      renderLogs([]);
    });
}
// Tab切换到日志时自动刷新
const tabLogsBtn = document.getElementById('tab-logs');
if (tabLogsBtn) {
    tabLogsBtn.addEventListener('click', fetchLogs);
}
// 拉取游戏房间并渲染（如有需要）
function fetchGames() {
  showSkeleton('matching-rooms-list', 3);
  // 这里假设你有API返回所有游戏房间
  fetch('/api/rooms?tag=game')
    .then(res => res.ok ? res.json() : [])
    .then(games => {
      renderGames(Array.isArray(games) ? games : []);
    })
    .catch(() => {
      renderGames([]);
    });
}
// 优化游戏房间区渲染
function renderGames(games) {
    games = Array.isArray(games) ? games : [];
    const gamesList = document.getElementById('matching-rooms-list');
    gamesList.innerHTML = '';
    if (!games.length) {
        gamesList.innerHTML = '<div class="text-center p-6 bg-gray-50 rounded-lg border border-gray-200 shadow-sm animate-fade-in">' +
            '<i class="fa fa-gamepad text-primary text-2xl mb-2"></i>' +
            '<p class="text-gray-600 font-medium">暂无游戏房间</p>' +
            '<p class="text-gray-500 text-sm mt-1">您可以在房间列表创建新游戏房间</p>' +
            '</div>';
        return;
    }
    games.forEach(game => {
        if (!game || typeof game !== 'object') return;
        const card = document.createElement('div');
        card.className = 'game-item bg-white rounded-xl shadow-md hover:shadow-xl transition-shadow p-4 flex items-center justify-between animate-fade-in mb-2';
        card.innerHTML = `
          <div class="flex items-center">
            <i class="fa fa-gamepad text-primary text-2xl mr-2"></i>
            <span class="font-semibold text-lg">${game.name || '未知游戏'}</span>
            <span class="text-xs bg-gray-100 px-2 py-1 rounded-full ml-2">${game.online || 0}人在线</span>
                    </div>
          <button class="modern-btn px-3 py-1 text-sm" onclick="window.location.href='/static/${game.page}?room_id=${game.room_id}'">进入</button>
        `;
        gamesList.appendChild(card);
    });
}
// Tab切换到游戏时自动刷新
const tabGamesBtn = document.getElementById('tab-games');
if (tabGamesBtn) {
    tabGamesBtn.addEventListener('click', () => {
      renderGameCards();
      renderGameOnlineCounts();
      if (window.gameOnlineInterval) clearInterval(window.gameOnlineInterval);
      window.gameOnlineInterval = setInterval(renderGameOnlineCounts, 5000);
    });
}

    // 1. 创建房间功能
    const createRoomBtn = document.getElementById('create-room-btn');
    const createRoomModal = document.getElementById('create-room-modal');
    const closeModalBtn = document.getElementById('close-modal-btn');
    const cancelCreateRoomBtn = document.getElementById('cancel-create-room-btn');
    const confirmCreateRoomBtn = document.getElementById('confirm-create-room-btn');
    const roomNameInput = document.getElementById('room-name');

    if (createRoomBtn && createRoomModal) {
      createRoomBtn.onclick = () => {
        createRoomModal.classList.remove('hidden');
        roomNameInput.value = '';
        roomNameInput.focus();
      };
    }
    if (closeModalBtn) closeModalBtn.onclick = () => createRoomModal.classList.add('hidden');
    if (cancelCreateRoomBtn) cancelCreateRoomBtn.onclick = () => createRoomModal.classList.add('hidden');
    if (confirmCreateRoomBtn) {
      confirmCreateRoomBtn.onclick = () => {
        const name = roomNameInput.value.trim();
        if (!name) {
          showToast('请输入房间名称', 'error');
          return;
        }
        if (!currentUser || !currentUser.userId) {
          showToast('请先登录后再创建房间', 'error');
          createRoomModal.classList.add('hidden');
                return;
            }
        fetch('/api/rooms', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-User-Id': currentUser.userId,
            'X-User-Name': encodeURIComponent(currentUser.username)
          },
          body: JSON.stringify({ name })
        })
                            .then(res => {
          if (!res.ok) throw new Error('创建房间失败');
          return res.json();
        })
        .then(data => {
          showToast('房间创建成功', 'success');
          createRoomModal.classList.add('hidden');
          fetchRooms();
          // 跳转到新房间
          joinRoom(data.room_id, name); // 用后端返回的 room_id
                            })
                            .catch(err => showToast(err.message, 'error'));
      };
    }

    // 2. 游戏空间panel显示三大游戏卡片
    function renderGameCards() {
      const gamesList = document.getElementById('matching-rooms-list');
      if (!gamesList) return;
      gamesList.innerHTML = `
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <div class="game-card modern-card p-6 flex flex-col items-center animate-fade-in">
            <i class="fa fa-gamepad text-green-500 text-4xl mb-2"></i>
            <div class="font-bold text-lg mb-1">贪吃蛇</div>
            <div id="snake-online" class="text-xs text-gray-500 mb-2">在线0</div>
            <button id="enter-snake" class="modern-btn px-4 py-2">进入</button>
          </div>
          <div class="game-card modern-card p-6 flex flex-col items-center animate-fade-in">
            <i class="fa fa-gamepad text-blue-500 text-4xl mb-2"></i>
            <div class="font-bold text-lg mb-1">五子棋</div>
            <div id="gomoku-online" class="text-xs text-gray-500 mb-2">在线0</div>
            <button id="enter-gomoku" class="modern-btn px-4 py-2">进入</button>
          </div>
          <div class="game-card modern-card p-6 flex flex-col items-center animate-fade-in">
            <i class="fa fa-gamepad text-yellow-500 text-4xl mb-2"></i>
            <div class="font-bold text-lg mb-1">井字棋</div>
            <div id="tictactoe-online" class="text-xs text-gray-500 mb-2">在线0</div>
            <button id="enter-tictactoe" class="modern-btn px-4 py-2">进入</button>
          </div>
        </div>
      `;
      // 绑定进入按钮
      document.getElementById('enter-snake').onclick = function() {
        createAndEnterGameRoom('snake', 'snake.html');
      };
      document.getElementById('enter-gomoku').onclick = function() {
        createAndEnterGameRoom('gomoku', 'gomoku.html');
      };
      document.getElementById('enter-tictactoe').onclick = function() {
        createAndEnterGameRoom('tictactoe', 'tictactoe.html');
      };
    }
    function createAndEnterGameRoom(gameName, page) {
      if (!currentUser) {
        showToast('请先登录', 'error');
                return;
            }
      fetch('/api/rooms', {
                method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-User-Id': currentUser.userId,
          'X-User-Name': encodeURIComponent(currentUser.username)
        },
        body: JSON.stringify({ name: gameName, tag: 'game' })
            })
                .then(res => {
        if (!res.ok) throw new Error('创建房间失败');
        return res.json();
      })
      .then(data => {
        window.location.href = `/static/${page}?room_id=${data.room_id}`;
      })
      .catch(() => {
        showToast('创建房间失败，请重试', 'error');
      });
    }
    // 游戏区Tab切换时渲染卡片和刷新在线人数
    if (tabGamesBtn) {
      tabGamesBtn.addEventListener('click', () => {
        renderGameCards();
        renderGameOnlineCounts();
        if (window.gameOnlineInterval) clearInterval(window.gameOnlineInterval);
        window.gameOnlineInterval = setInterval(renderGameOnlineCounts, 5000);
      });
    }
    // 获取各游戏在线人数
    function renderGameOnlineCounts() {
            fetch('/api/rooms')
        .then(res => res.ok ? res.json() : [])
                .then(rooms => {
          rooms = Array.isArray(rooms) ? rooms : [];
          const online = { snake: 0, gomoku: 0, tictactoe: 0 };
          rooms.forEach(room => {
            if (room.name === 'snake') online.snake += (room.user_count || 0);
            if (room.name === 'gomoku') online.gomoku += (room.user_count || 0);
            if (room.name === 'tictactoe') online.tictactoe += (room.user_count || 0);
          });
          document.getElementById('snake-online').textContent = `在线${online.snake}`;
          document.getElementById('gomoku-online').textContent = `在线${online.gomoku}`;
          document.getElementById('tictactoe-online').textContent = `在线${online.tictactoe}`;
        });
    }

    // 3. 个人中心panel展示用户信息
        function renderProfile() {
            if (!currentUser) return;
            document.getElementById('profile-username').textContent = currentUser.username;
            document.getElementById('profile-userid').textContent = 'ID: ' + currentUser.userId;
            document.getElementById('profile-avatar').src = currentUser.avatar || 'https://cdn.jsdelivr.net/gh/identicons/jasonlong.png';
    }
    // 个人中心Tab点击时跳转到profile.html
    const tabProfileBtn = document.getElementById('tab-profile');
    if (tabProfileBtn) {
      tabProfileBtn.addEventListener('click', function() {
        window.location.href = '/static/profile.html';
      });
    }
    // 退出按钮逻辑：清除localStorage并跳转到profile.html
    if (document.getElementById('logout-btn')) {
      document.getElementById('logout-btn').onclick = function() {
        logoutAndRedirect();
      };
    }
    if (document.getElementById('mobile-logout-btn')) {
      document.getElementById('mobile-logout-btn').onclick = function() {
        logoutAndRedirect();
      };
    }
    // 页面加载时自动渲染个人信息
    window.addEventListener('DOMContentLoaded', renderProfile);

    // 聊天面板 WebSocket 逻辑
    let ws = null;
    let currentRoomId = null;
    let currentRoomName = '';
    let currentRoomUserCount = 0;
    let wsReconnectTimer = null;

    // 加入房间函数，供房间卡片点击“进入”时调用
    function joinRoom(roomId, roomName) {
      if (!currentUser) {
        showToast('请先登录', 'error');
        return;
      }
      // 切换到聊天面板
      Object.values(allTabs).forEach(panelId => {
        document.getElementById(panelId).classList.add('hidden');
      });
      document.getElementById('chat-panel').classList.remove('hidden');
      // 设置当前房间信息
      currentRoomId = roomId;
      currentRoomName = roomName;
      document.getElementById('current-room-name').textContent = roomName;
      document.getElementById('messages').innerHTML = '';
      document.getElementById('current-room-user-count').textContent = '';
      // 建立 WebSocket 连接
      connectChatWS();
      // 聊天输入框自动聚焦
      setTimeout(() => {
        const input = document.getElementById('message-input');
        if (input) input.focus();
        scrollMessagesToBottom();
      }, 200);
    }

    function connectChatWS() {
      if (ws) {
        ws.close();
        ws = null;
      }
      if (!currentUser || !currentRoomId) return;
      const wsUrl = `ws://${location.host}/ws?user_id=${currentUser.userId}&user_name=${encodeURIComponent(currentUser.username)}&room_id=${currentRoomId}`;
      ws = new WebSocket(wsUrl);
      ws.onopen = function() {
        showToast('已加入房间', 'success');
        // 拉取历史消息
        fetch(`/api/rooms/${currentRoomId}/messages`).then(res => res.ok ? res.json() : []).then(renderMessages);
        // 拉取在线用户
        fetch(`/api/rooms/users?room_id=${currentRoomId}`).then(res => res.ok ? res.json() : []).then(updateUserCount);
      };
      ws.onmessage = function(e) {
        let msg = {};
        try { msg = JSON.parse(e.data); } catch { return; }
        if (msg.type === 0) {
          // 文本消息
          appendMessage(msg, msg.user_id === currentUser.userId);
        } else if (msg.type === 1) {
          // 加入
          appendSystemMessage(`${msg.user_name || msg.user_id} 加入了房间`);
          fetch(`/api/rooms/users?room_id=${currentRoomId}`).then(res => res.ok ? res.json() : []).then(updateUserCount);
        } else if (msg.type === 2) {
          // 离开
          appendSystemMessage(`${msg.user_name || msg.user_id} 离开了房间`);
          fetch(`/api/rooms/users?room_id=${currentRoomId}`).then(res => res.ok ? res.json() : []).then(updateUserCount);
        }
      };
      ws.onclose = function() {
        showToast('已离开房间', 'info');
        if (wsReconnectTimer) clearTimeout(wsReconnectTimer);
           // 只有当前还在聊天面板时才重连
          if (!document.getElementById('chat-panel').classList.contains('hidden')) {
            wsReconnectTimer = setTimeout(connectChatWS, 3000);
          }
      };
      ws.onerror = function() {
        showToast('WebSocket 连接异常', 'error');
      };
    }

    // 发送消息
    document.getElementById('send-message-btn').onclick = sendChatMessage;
    document.getElementById('message-input').onkeydown = function(e) {
      if (e.key === 'Enter') sendChatMessage();
    };
    function sendChatMessage() {
      const input = document.getElementById('message-input');
      const text = input.value.trim();
      if (!text || !ws || ws.readyState !== WebSocket.OPEN) return;
      const msg = {
        type: 0,
        user_id: currentUser.userId,
        user_name: currentUser.username,
        content: text,
        // 修复：使用整数时间戳（毫秒级）
        time: Date.now() // 正确：返回整数毫秒数
       // 或使用秒级整数时间戳：Math.floor(Date.now() / 1000)
      };
      ws.send(JSON.stringify(msg));
      // 本地立即渲染消息
      appendMessage(msg, true);
      input.value = '';
      input.focus();
      scrollMessagesToBottom();
    }

    // 渲染消息
    function renderMessages(msgs) {
      const messagesDiv = document.getElementById('messages');
      messagesDiv.innerHTML = '';
      (Array.isArray(msgs) ? msgs : []).forEach(msg => {
        appendMessage(msg, msg.user_id === currentUser.userId, false);
      });
      scrollMessagesToBottom();
    }
    function appendMessage(msg, isSelf, autoScroll = true) {
      const messagesDiv = document.getElementById('messages');
      const wrapper = document.createElement('div');
      wrapper.className = 'flex w-full mb-2 ' + (isSelf ? 'justify-end' : 'justify-start');
      // 头像/首字母
      const avatar = document.createElement('div');
      avatar.className = 'avatar-optimized flex-shrink-0';
      if (msg.avatar) {
        avatar.innerHTML = `<img src="${msg.avatar}" alt="avatar">`;
      } else {
        avatar.textContent = (msg.user_name || msg.user_id || '?').slice(0,1).toUpperCase();
      }
      // 气泡和时间容器
      const msgCol = document.createElement('div');
      msgCol.className = 'flex flex-col ' + (isSelf ? 'items-end' : 'items-start');
      // 时间单独一行
      const timeDiv = document.createElement('div');
      timeDiv.className = 'text-xs text-gray-400 mb-1';
      timeDiv.style.textAlign = isSelf ? 'right' : 'left';
      timeDiv.textContent = formatTime(msg.time);
      msgCol.appendChild(timeDiv);
      // 气泡和已读包裹
      const bubbleReadCol = document.createElement('div');
      bubbleReadCol.className = 'flex flex-col items-end';
      // 气泡内容
      const bubble = document.createElement('div');
      bubble.className = 'message-in';
      bubble.style.background = isSelf
        ? 'linear-gradient(135deg,#6366f1,#818cf8)' : 'linear-gradient(135deg,#e0e7ff,#f8fafc)';
      bubble.style.color = isSelf ? '#fff' : '#334155';
      bubble.style.boxShadow = '0 2px 8px 0 rgba(80,80,180,0.08)';
      bubble.style.borderRadius = '1.5rem';
      bubble.style.wordBreak = 'break-word';
      bubble.style.display = 'inline-block';
      bubble.style.position = 'relative';
      bubble.innerHTML = `<div class=\"text-base\">${escapeHTML(msg.content)}</div>`;
      bubbleReadCol.appendChild(bubble);
      // 已读状态（本地模拟：自己发的消息，刚发出为未读，1秒后变已读）
      if (isSelf) {
        let status = msg._read ? '✓ 已读' : '✓ 未读';
        const statusDiv = document.createElement('div');
        statusDiv.className = 'read-status-row';
        statusDiv.textContent = status;
        bubbleReadCol.appendChild(statusDiv);
        // 本地模拟：1秒后变已读
        if (!msg._read) {
          setTimeout(() => {
            statusDiv.textContent = '✓ 已读';
            msg._read = true;
          }, 1000);
        }
      }
      msgCol.appendChild(bubbleReadCol);
      // 用户名在头像下方
      const nameDiv = document.createElement('div');
      nameDiv.className = 'text-xs text-gray-500 text-center mt-1';
      nameDiv.textContent = msg.user_name || msg.user_id;
      avatar.appendChild(nameDiv);
      // 结构拼装
      if (isSelf) {
        wrapper.appendChild(msgCol);
        wrapper.appendChild(avatar);
      } else {
        wrapper.appendChild(avatar);
        wrapper.appendChild(msgCol);
      }
      messagesDiv.appendChild(wrapper);
      if (autoScroll !== false) scrollMessagesToBottom();
    }
    function appendSystemMessage(text) {
      const messagesDiv = document.getElementById('messages');
      const sys = document.createElement('div');
      sys.className = 'text-center text-xs text-gray-400 my-2';
      sys.textContent = text;
      messagesDiv.appendChild(sys);
      scrollMessagesToBottom();
    }
    function updateUserCount(users) {
      currentRoomUserCount = Array.isArray(users) ? users.length : 0;
      document.getElementById('current-room-user-count').textContent = `在线人数：${currentRoomUserCount}`;
    }
    function formatTime(ts) {
      if (!ts) return '';
      const d = new Date(ts * 1000);
      return d.toLocaleTimeString();
    }
    function escapeHTML(str) {
      return String(str).replace(/[&<>"']/g, function (c) {
        return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#39;'}[c];
      });
    }
    function scrollMessagesToBottom() {
      // 让消息区容器滚动到底部
      const container = document.getElementById('messages-container');
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    }
    // 聊天面板返回按钮逻辑
    document.getElementById('back-to-rooms-btn').onclick = function() {
      if (ws) { ws.close(); ws = null; }
      document.getElementById('chat-panel').classList.add('hidden');
      document.getElementById('rooms-panel').classList.remove('hidden');
    };

    // 登录/登出逻辑
    function updateAuthUI() {
      const userInfo = document.getElementById('user-info');
      const currentUserSpan = document.getElementById('current-user');
      const loginBtn = document.getElementById('login-btn');
      const logoutBtn = document.getElementById('logout-btn');
      const mobileLoginBtn = document.getElementById('mobile-login-btn');
      const mobileLogoutBtn = document.getElementById('mobile-logout-btn');
      if (currentUser) {
        if (userInfo) userInfo.classList.remove('hidden');
        if (currentUserSpan) {
          currentUserSpan.textContent = currentUser.username;
          currentUserSpan.classList.remove('hidden');
        }
        if (loginBtn) loginBtn.classList.add('hidden');
        if (logoutBtn) logoutBtn.classList.remove('hidden');
        if (mobileLoginBtn) mobileLoginBtn.classList.add('hidden');
        if (mobileLogoutBtn) mobileLogoutBtn.classList.remove('hidden');
      } else {
        if (userInfo) userInfo.classList.remove('hidden');
        if (currentUserSpan) currentUserSpan.classList.add('hidden');
        if (loginBtn) loginBtn.classList.remove('hidden');
        if (logoutBtn) logoutBtn.classList.add('hidden');
        if (mobileLoginBtn) mobileLoginBtn.classList.remove('hidden');
        if (mobileLogoutBtn) mobileLogoutBtn.classList.add('hidden');
      }
    }
    // 页面加载时更新UI
    window.addEventListener('DOMContentLoaded', function() {
      updateAuthUI();
    });
    window.addEventListener('DOMContentLoaded', fetchRooms);
    </script>
</body>
</html>